package com.ryder.petmatediarybackend.module.file.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.ryder.petmatediarybackend.common.response.Result;
import com.ryder.petmatediarybackend.module.file.service.FileUploadService;
import com.ryder.petmatediarybackend.module.file.vo.FileUploadVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.constraints.NotBlank;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.List;

/**
 * 描述: 文件上传管理接口
 *
 * @author Ryder
 * @version 1.0
 * @since 1.0
 * 更新日期: 2025/10/30
 */
@Slf4j
@Tag(name = "文件上传管理", description = "文件上传、删除接口（支持单张或多张）")
@RestController
@RequestMapping("/upload")
@RequiredArgsConstructor
@Validated
public class FileUploadController {

    private final FileUploadService fileUploadService;

    @Operation(summary = "上传文件", description = "支持单张或多张文件上传，根据业务类型自动分配存储路径，需要登录",
               security = @SecurityRequirement(name = "Authorization"))
    @PostMapping("/image")
    public Result<List<FileUploadVO>> uploadImage(
            @Parameter(description = "文件列表（可单个或多个）", required = true)
            @RequestParam("files") MultipartFile[] files,
            
            @Parameter(description = "业务类型", required = true, 
                      example = "USER_AVATAR",
                      schema = @io.swagger.v3.oas.annotations.media.Schema(
                              allowableValues = {"USER_AVATAR", "PET_AVATAR", "PET_ALBUM", "DIARY_IMAGE", 
                                                "MOMENT_IMAGE", "QUALIFICATION", "SHOP_PET_COLLECTION", "SHOP_PRODUCT_COLLECTION"}))
            @RequestParam("bizType") @NotBlank(message = "业务类型不能为空") String bizType) {

        // 通过satoken获取用户ID
        Long userId = StpUtil.getLoginIdAsLong();
        log.info("[文件上传] 开始上传, userId={}, bizType={}, 文件数量={}", userId, bizType, files.length);

        // 以免多图片，转成列表
        List<MultipartFile> fileList = Arrays.asList(files);

        // 执行真正核心操作
        List<FileUploadVO> result = fileUploadService.uploadFiles(fileList, bizType, userId);
        
        log.info("[文件上传] 上传完成, userId={}, bizType={}, 成功数量={}", userId, bizType, result.size());
        return Result.ok(result);
    }

    @Operation(summary = "删除文件", description = "根据文件唯一标识删除文件，仅能删除自己上传的文件，需要登录",
               security = @SecurityRequirement(name = "Authorization"))
    @DeleteMapping("/image")
    public Result<String> deleteImage(
            @Parameter(description = "文件唯一标识", required = true, example = "avatar/pet/123/1730280000_abc123.jpg")
            @RequestParam("fileKey") @NotBlank(message = "文件标识不能为空") String fileKey) {
        
        Long userId = StpUtil.getLoginIdAsLong();
        log.info("[文件删除] 开始删除, userId={}, fileKey={}", userId, fileKey);
        
        fileUploadService.deleteFile(fileKey, userId);
        
        log.info("[文件删除] 删除完成, userId={}, fileKey={}", userId, fileKey);
        return Result.ok("删除成功");
    }
}
